package com.xhsj.user.utils;

import com.xhsj.user.hr.process.hrBecomeRegular.query.QuestionAndAnswerDataQuery;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 树形处理
 * 
 * @author 刘庆花
 * @date 2019年9月9日
 */
public class QuestionAndAnswerTreeUtils {
    /**
     * 根据父节点的ID获取所有子节点
     * 
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public static List<QuestionAndAnswerDataQuery> getChildPerms(List<QuestionAndAnswerDataQuery> list, Long parentId) {
        List<QuestionAndAnswerDataQuery> returnList = new ArrayList();
        for (Iterator<QuestionAndAnswerDataQuery> iterator = list.iterator(); iterator.hasNext();) {
            QuestionAndAnswerDataQuery t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().longValue() == parentId.longValue()) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     * 
     * @param list
     * @param t
     */
    private static void recursionFn(List<QuestionAndAnswerDataQuery> list, QuestionAndAnswerDataQuery t)
    {
        // 得到子节点列表
        List<QuestionAndAnswerDataQuery> childList = getChildList(list, t);
        t.setChildren(childList);
        for (QuestionAndAnswerDataQuery tChild : childList)
        {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<QuestionAndAnswerDataQuery> it = childList.iterator();
                while (it.hasNext())
                {
                    QuestionAndAnswerDataQuery n = it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     * @param list
     * @param t
     * @return
     */
    private static List<QuestionAndAnswerDataQuery> getChildList(List<QuestionAndAnswerDataQuery> list, QuestionAndAnswerDataQuery t) {

        List<QuestionAndAnswerDataQuery> tlist = new ArrayList();
        Iterator<QuestionAndAnswerDataQuery> it = list.iterator();
        while (it.hasNext()) {
            QuestionAndAnswerDataQuery n =  it.next();
            if (n.getParentId().longValue() == t.getQuestionId().longValue())
            {
                tlist.add(n);
            }

        }

        return tlist;
    }


    /**
     * 判断是否有子节点
     * @param list
     * @param t
     * @return
     */
    private static boolean hasChild(List<QuestionAndAnswerDataQuery> list, QuestionAndAnswerDataQuery t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
